// 替换 openApi title
function __replaceOpenApiTitle(open) {
  if (!open && window.__replaceOpenApiTitleId) {
    cancelAnimationFrame(window.__replaceOpenApiTitleId)
    window.__replaceOpenApiTitleId = null
  }
  if (open && location.host === 'openapi.58corp.com') {
    window.__replaceOpenApiTitleId = null
    const cb = () => {
      const _el = document.querySelector('.markdown-top-title')
      if (_el) {
        if (document.title === _el.innerText.slice(5)) {
          cancelAnimationFrame(window.__replaceOpenApiTitleId)
        }
        document.title = _el.innerText.slice(5)
      }
      window.__replaceOpenApiTitleId = requestAnimationFrame(cb)
    }
    cb()
  }  
}

__replaceOpenApiTitle(true)

const doc = document
// eslint-disable-next-line no-undef
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  // 获取 cookies
  if (request.message === 'GET_COOKIES') {
    // 获取cookie
    const _cookies = doc.cookie
    const cookieList = []
    if (_cookies) {
      _cookies.split(';').forEach(item => {
        const i = item.split('=')
        cookieList.push({
          key: i[0] || '',
          value: i[1] || '',
        })
      })
    }
    // 发送数据 
    sendResponse(cookieList)
  }
  // 设置 cookies 追加
  if (request.message === 'SET_COOKIES_PUSH') {
    const _obj = {}
    const obj = {}
    doc.cookie.split(';').forEach(i => {
      const _ = i.split('=')
      obj[_[0]] = _[1]
    })
    request.data.forEach(i => {
      const _ = i.split('=')
      if (obj[_[0]] && obj[_[0]] === _[1]) {
        delete _obj[_[0]]
      } else {
        _obj[_[0]] = _[1]
      }
    })
    for (let key in _obj) {
      doc.cookie = `${key}=${_obj[key]}`
    }
    sendResponse()
  }
})
